<template>
  <a-spin :spinning="spinning">
    <div class="main-box">
      <div class="left-box">
        <a-card :body-style="{ padding: '0px', 'min-height': 'calc(100vh - 100px)' }">
          <a-button
            size="large"
            style="margin: 10px auto; border-radius: 3px !important"
            ghost
            type="primary"
            block
            @click="showWindow(undefined, '', '')"
          >
            新建角色
          </a-button>
          <a-menu
            v-if="activeMenu"
            style="width: 100%"
            :default-selected-keys="[activeMenu]"
            mode="inline"
            @click="handleClick"
          >
            <a-menu-item v-for="item in roleList" :key="item.id">
              <span>{{ item.roleName }}</span>
              <span v-if="item.id == activeMenu && item.internalRoleFlag === 0">
                <a-icon type="edit" @click="showWindow(item.id, item.roleName, item.roleCode)" />
                <a-popconfirm title="确定删除吗？" ok-text="确定" cancel-text="取消" @confirm="deleteRole(item.id)">
                  <a-icon type="delete" />
                </a-popconfirm>
              </span>
            </a-menu-item>
          </a-menu>
        </a-card>
      </div>
      <div class="right-box">
        <a-card :body-style="{ padding: '10px', 'min-height': 'calc(100vh - 100px)' }">
          <a-table
            bordered
            ref="table"
            size="middle"
            :scroll="{ x: true }"
            rowKey="key"
            :columns="tableColumn"
            :dataSource="treeList"
            :loading="tableLoading"
            :pagination="false"
            class="j-table-force-nowrap"
          >
            <template slot="dataRoles" slot-scope="text, record">
              <a-radio-group v-model="record.dataValue">
                <a-radio v-for="(item, index) in record.title3" :key="index" :style="radioStyle" :value="item.id">
                  {{ item.ruleName }}
                </a-radio>
              </a-radio-group>
            </template>
          </a-table>
          {{ treeList }}
        </a-card>
      </div>
    </div>
    <a-modal
      :title="formParam.id ? '编辑角色' : '新建角色'"
      :visible="visible"
      :width="600"
      :body-style="{ padding: '30px 50px 0px 50px' }"
      @cancel="handleCancel"
    >
      <a-form-model
        ref="formParam"
        :model="formParam"
        :rules="{
          roleName: [
            { required: true, message: '请输入角色名称', trigger: 'change' },
            { min: 1, max: 6, message: '长度在1-6个字符', trigger: 'blur' },
          ],
          roleCode: [{ required: true, validator: checkNum, trigger: 'change' }],
        }"
        layout="vertical"
      >
        <a-form-model-item ref="roleName" label="角色名称" prop="roleName">
          <a-input placeholder="最多允许输入6个字符" v-model="formParam.roleName" />
        </a-form-model-item>
        <a-form-model-item ref="roleCode" label="角色编码" prop="roleCode">
          <a-input placeholder="最多允许输入20个字符" v-model="formParam.roleCode" />
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <div style="width: 100%; text-align: left; padding-left: 34px">
          <a-button
            @click="
              visible = false
              $refs.formParam.resetFields()
            "
            >取消</a-button
          >
          <a-button type="primary" :loading="btnLoading" @click="handleOk">确定</a-button>
        </div>
      </template>
    </a-modal>
  </a-spin>
</template>

<script>
import {
  roleGetRoles,
  roleCheckRoleCode,
  roleAdd,
  roleDelete,
  roleEdit,
  roleQueryTreeList,
  roleDatarule,
} from '@/api/authorityManagement'
export default {
  name: 'AuthorityManagementRoleManager',
  data() {
    return {
      spinning: false,
      roleList: [],
      activeMenu: null,
      visible: false,
      formParam: {
        id: undefined,
        roleName: '',
        roleCode: '',
      },
      btnLoading: false,
      treeList: [],
      tableLoading: false,
      tableColumn: [
        {
          title: '一级菜单',
          key: '1',
          dataIndex: 'title1',
          customRender: (text, record, index) => {
            return {
              attrs: {
                rowSpan: record.rowSpan,
              },
              children: text,
            }
          },
        },
        {
          title: '二级菜单',
          key: '2',
          dataIndex: 'title2',
          customRender: (text, record, index) => {
            return text
          },
        },
        {
          title: '数据权限',
          key: '3',
          scopedSlots: { customRender: 'dataRoles' },
          // customRender: (text, record, index) => {
          //   return (
          //     <div style="text-overflow: ellipsis;overflow: hidden;white-space: nowrap;">
          //       {text.map((i) => {
          //         return <span>{i.ruleName}</span>
          //       })}
          //     </div>
          //   )
          // },
        },
      ],
      radioStyle: {
        display: 'block',
        height: '30px',
        lineHeight: '30px',
      },
    }
  },
  created() {
    this.getRoles()
  },
  methods: {
    async getRoles() {
      try {
        this.spinning = true
        const res = await roleGetRoles()
        if (res.result && res.result.length) {
          if (!this.activeMenu) {
            //首次选中
            this.activeMenu = res.result[0].id
          }
          this.getTreeData()
          this.roleList = res.result
        }
        this.spinning = false
      } catch (e) {
        this.spinning = false
        console.log(e)
      }
    },
    showWindow(id, name, code) {
      this.formParam.id = id
      this.formParam.roleName = name
      this.formParam.roleCode = code
      this.visible = true
    },
    handleClick(e) {
      this.activeMenu = e.key

      this.getTreeData()
    },
    async deleteRole(id) {
      try {
        const res = await roleDelete({ id: id })
        if (res.success) {
          this.activeMenu = ''
          this.getRoles()
          this.$notification.success({ message: '系统提示', description: res.message })
        } else {
          this.$notification.error({ message: '系统提示', description: res.message })
        }
      } catch (e) {}
    },
    async checkNum(a, b, c) {
      try {
        if (b === '') {
          c('请输入角色编码')
        }
        if (b.length > 20) {
          c('长度在1-20个字符')
        }
        if (!/^[a-zA-Z0-9_]+$/.test(b)) {
          c('请输入正确的编码')
        }
        const res = await roleCheckRoleCode({ id: this.formParam.id, roleCode: this.formParam.roleCode })
        if (!res.success) {
          c(res.message)
        }
      } catch (error) {
        c('查重失败')
      }
    },
    handleOk() {
      this.$refs.formParam.validate(async (valid) => {
        if (valid) {
          const api = this.formParam.id ? roleEdit : roleAdd
          try {
            this.btnLoading = true
            const res = await api(this.formParam)
            if (res.success) {
              this.visible = false
              this.getRoles()
              this.$refs.formParam.resetFields()
              this.$notification.success({ message: '系统提示', description: res.message })
            } else {
              this.$notification.error({ message: '系统提示', description: res.message })
            }
            this.btnLoading = false
          } catch (e) {
            this.btnLoading = false
            this.$notification.error({ message: '系统提示', description: e.toString() })
          }
        }
      })
    },
    handleCancel() {
      this.visible = false
      this.$refs.formParam.resetFields()
    },
    async getTreeData() {
      try {
        this.spinning = true
        const res = await roleQueryTreeList()
        this.treeList = this.handleTableData(res.result.treeList)
        this.spinning = false
      } catch (e) {
        this.spinning = false
      }
    },
    getDataRole(param) {
      return new Promise(async (resolve, reject) => {
        const res = await roleDatarule(param)
        if (res.success) {
          resolve(res.result.datarule)
        } else {
          resolve([])
        }
      })
    },
    //把树结构转换平级结构
    handleTableData(data) {
      let arr = []
      if (Array.isArray(data)) {
        let data1 = data
        data1.forEach((item1) => {
          if (item1.children && item1.children.length) {
            //多层
            item1.children.forEach(async (item2, index2) => {
              let obj = item2
              if (index2 === 0) {
                obj.rowSpan = item1.children.length
              } else {
                obj.rowSpan = 0
              }
              obj.title1 = item1.slotTitle
              obj.title2 = item2.slotTitle
              if (item2.ruleFlag === 1) {
                //请求其他接口
                obj.title3 = await this.getDataRole({ id1: item2.key, id2: this.activeMenu })
                obj.dataValue = ''
              } else {
                obj.title3 = []
              }
              delete obj.children
              arr.push(obj)
            })
          } else {
            //只有一层
            let obj = item1
            obj.rowSpan = 1
            obj.title1 = item1.slotTitle
            obj.title2 = ''
            obj.title3 = []
            delete obj.children
            arr.push(obj)
          }
        })
        return arr
      } else {
        return []
      }
    },
  },
}
</script>

<style lang="less" scoped>
.main-box {
  display: flex;
  flex-flow: row nowrap;
  .left-box {
    width: 320px;
    .ant-menu-item-selected {
      display: flex;
      justify-content: space-between;
      background: #d2e9ff;
    }
  }
  .right-box {
    margin-left: 20px;
    flex: 1;
  }
}
</style>